/**
 * 客户管理
 */
define(function (require, exports, module) {
    require('authorize');
    var util = require('util');
    var ui = require('ui');
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("datepicker");
    require("pagination");
    require('service/ng_service/projectService');
    require("permission");
    require('global');
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/customer-manage/"; //api前缀

    angular.module('app', ['ngRoute', 'ngUI', 'ProjectService'])
        .controller('MainController', ['$rootScope', '$scope', '$http', '$location', '$routeParams', 'projectList',
            function ($rootScope, $scope, $http, $location, $routeParams, projectList) {
                //搜索下拉选项数据
                $scope.search = {
                    type: "1", keyword: "",
                    fieldList: [
                        {value: '1', text: '客户姓名'},
                        {value: '2', text: '客户电话'},
                        {value: '3', text: '经纪人姓名'},
                        {value: '4', text: '经纪人电话'}
                    ]
                };
                //按关键字搜索
                function searchByKeyword() {
                    var params = {
                        projectId: $scope.projectId,
                        curPage: $scope.pageIndex,
                        type: $scope.search.type,
                        placeholder: $scope.search.keyword,
                        pageSize: $scope.filter.pageSize
                    };
                    $scope.loading = true;
                    return $http
                        .get(api_prefix + "basis-search", {params: params})
                        .then(function (res) {
                            $scope.loading = false;
                            var retCode = res.data.retCode;
                            if (retCode == 0) {
                                var data = res.data.data;
                                $scope.list = data.items;
                                _.each($scope.list, function (item) {
                                    if (+new Date(item.save_enddate) <= +new Date(SERVER_TIME.split(' ')[0])) {
                                        item._hasExpires = true
                                    }
                                });
                                $scope.total = data.total;
                            } else {
                                ui.showErrTip(res.data.errMsg);
                                return false;
                            }
                        })
                }

                /*搜索按钮点击*/
                $scope.getSearchData = function () {
                    $scope.searchStatus = '1';
                    $scope.pageIndex = 1;
                    searchByKeyword();
                };
                //经济人身份
                $scope.changeBrokerIdentity = function (event, value) {
                    //切换身份时清空子集公司

                    $scope.filter.belongsCompany = [];
                    $scope.selectedBrokerIdentity = value;
                    $scope.owerCompanys = $scope.getOwerCompanys();
                    for (var i = 0, item; item = $scope.owerCompanys[i]; i++) {
                        $scope.owerCompanys[i].checked = false;
                    }
                    $scope.owerCompanyCheckAll = false;
                    if (event) {
                        ui.changeTipsArrow(event.currentTarget);
                    }
                };
                // 获取所属公司
                $scope.getOwerCompanys = function () {
                    switch ($scope.selectedBrokerIdentity) {
                        case '9003':
                            // 代理公司
                            return $scope.agentCompany || [];

                        case '9005':
                            // 中介公司
                            return $scope.agencyCompany || [];

                        case '9006':
                            // 合作伙伴
                            return $scope.partnerCompany || [];

                        case '9108':
                            // 中介机构
                            return $scope.agency || [];

                        default:
                            return [];
                    }
                };

                // 代理公司
                $scope.loading = true;
                $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agentCompany')
                    .then(function (res) {
                        var retCode = res.data.retCode;
                        if (retCode == 0) {
                            var data = res.data.data;
                            $scope.agentCompany = data;
                            for (var i = 0, item; item = $scope.agentCompany[i]; i++) {
                                if (item.Disabled == 1) {
                                    $scope.agentCompany.splice(i, 1);
                                    i--;
                                }
                            }
                        }
                        else {
                            ui.showErrTip(res.data.errMsg);
                            return false;
                        }
                    });
                // 中介公司
                $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agencyCompany')
                    .then(function (res) {
                        var retCode = res.data.retCode;
                        if (retCode == 0) {
                            var data = res.data.data;
                            $scope.agencyCompany = data;
                            for (var i = 0, item; item = $scope.agencyCompany[i]; i++) {
                                if (item.Disabled == 1) {
                                    $scope.agencyCompany.splice(i, 1);
                                    i--;
                                }
                            }
                        }
                        else {
                            ui.showErrTip(res.data.errMsg);
                            return false;
                        }
                    });
                // 合作伙伴
                $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=partnerCompany')
                    .then(function (res) {
                        var retCode = res.data.retCode;
                        if (retCode == 0) {
                            var data = res.data.data;
                            $scope.partnerCompany = data;
                            for (var i = 0, item; item = $scope.partnerCompany[i]; i++) {
                                if (item.Disabled == 1) {
                                    $scope.partnerCompany.splice(i, 1);
                                    i--;
                                }
                            }
                        }
                        else {
                            ui.showErrTip(res.data.errMsg);
                            return false;
                        }
                    });

                // 中介机构
                $http.get('/api/index.php?r=qmyx/broker/get-companys-by-token-and-code&paramCode=agency')
                    .then(function (res) {
                        var retCode = res.data.retCode;
                        if (retCode == 0) {
                            var data = res.data.data;
                            $scope.agency = data;
                            for (var i = 0, item; item = $scope.agency[i]; i++) {
                                if (item.Disabled == 1) {
                                    $scope.agency.splice(i, 1);
                                }
                            }
                        }
                        else {
                            ui.showErrTip(res.data.errMsg);
                            return false;
                        }
                    });

                // 全选/取消全选
                $scope.updateOwerCompanyCheckAll = function () {
                    var filterBelongsCompany = [];
                    for (var i = 0, item; item = $scope.owerCompanys[i]; i++) {
                        item.checked = $scope.owerCompanyCheckAll;
                        if (item.checked) {
                            if ($scope.selectedBrokerIdentity == 9108) {
                                filterBelongsCompany.push(item.b_agenciesId);
                            }
                            else {
                                filterBelongsCompany.push(item.Value);
                            }
                        }
                    }
                    if (filterBelongsCompany.length == 0) {
                        filterBelongsCompany = [];
                    }
                    $scope.filter.belongsCompany = filterBelongsCompany;
                };

                // 同步全选/取消全选
                $scope.updateOwerCompanyCheck = function () {
                    var checked = true;
                    var filterBelongsCompany = [];
                    for (var i = 0, item; item = $scope.owerCompanys[i]; i++) {
                        if (!item.checked) {
                            checked = false;
                        } else {
                            if ($scope.selectedBrokerIdentity == 9108) {
                                filterBelongsCompany.push(item.b_agenciesId);
                            }
                            else {
                                filterBelongsCompany.push(item.Value);
                            }

                        }
                    }


                    if (filterBelongsCompany.length == 0) {
                        filterBelongsCompany = [];
                    }
                    ;

                    $scope.filter.belongsCompany = filterBelongsCompany;
                    $scope.owerCompanyCheckAll = checked;
                };

                //客户状态
                $scope.clientList = [
                    {Text: '报备', selected: false, cstStatus: "2"},
                    {Text: '带看/到访', selected: false, cstStatus: "3"},
                    {Text: '交易', selected: false, cstStatus: "4"},
                    {Text: '结佣', selected: false, cstStatus: "5"}
                ];
                $scope.updataClientCheck = function () {

                    var clientList = $scope.clientList;
                    var filterCstStatus = [];
                    for (var i = 0, item; item = clientList[i]; i++) {
                        if (item.selected) {
                            filterCstStatus.push(item.cstStatus);
                        }
                    }
                    if (filterCstStatus.length == 0) {
                        filterCstStatus = [];
                    }
                    $scope.filter.cstStatus = filterCstStatus;
                };

                //审核状态
                $scope.ShenheList = [
                    {Text: '待审核/已申请', selected: false, shenhe: "1"},
                    {Text: '已接收/已带看/已到访/已审定', selected: false, shenhe: "2"},
                    {Text: '拒收', selected: false, shenhe: "3"},
                    {Text: '申诉中', selected: false, shenhe: "4"},
                    {Text: '已结佣', selected: false, shenhe: "5"},
                    {Text: '认筹', selected: false, shenhe: "6"},
                    {Text: '认购', selected: false, shenhe: "7"}
                    //{Text: '签约', selected: false, shenhe: "8"}
                ];
                $scope.updataShenheCheck = function () {
                    var ShenheList = $scope.ShenheList;
                    var filterShenhe = [];
                    for (var i = 0, item; item = ShenheList[i]; i++) {
                        if (item.selected) {
                            filterShenhe.push(item.shenhe);
                        }
                    }
                    if (filterShenhe.length == 0) {
                        filterShenhe = [];
                    }
                    $scope.filter.shenhe = filterShenhe;
                };

                //查询默认
                $scope.filter = {
                    belongsCompany: [],
                    shenhe: [],
                    cstStatus: [],
                    startDate: '',
                    endDate: '',
                    pageSize: 10,
                    // 撤销过滤
                    clearFilter: function () {
                        for (var i = 0, item; item = $scope.clientList[i]; i++) {
                            item.selected = false;
                        }
                        for (var i = 0, item; item = $scope.ShenheList[i]; i++) {
                            item.selected = false;
                        }

                        $scope.selectedBrokerIdentity = '';
                        $scope.owerCompanys = [];
                        $scope.filter.belongsCompany = [];
                        $scope.filter.cstStatus = [];
                        $scope.filter.shenhe = [];
                        $scope.filter.startDate = '';
                        $scope.filter.endDate = '';
                        $scope.getFilterData();
                    }
                };

                //获取查询数据
                function doGetFilter() {
                    var params = {
                        projId: $scope.projectId,
                        curPage: $scope.pageIndex,
                        brokerIdentity: $scope.selectedBrokerIdentity,
                        belongsCompany: $scope.filter.belongsCompany.join(","),
                        cstStatus: $scope.filter.cstStatus.join(","),
                        checkStatus: $scope.filter.shenhe.join(","),
                        sTime: $scope.filter.startDate,
                        eTime: $scope.filter.endDate,
                        pageSize: $scope.filter.pageSize
                    };
                    $scope.loading = true;
                    return $http
                        .get(api_prefix + "advanced-search", {params: params})
                        .then(function (res) {
                            $scope.loading = false;
                            var retCode = res.data.retCode;
                            if (retCode == 0) {
                                var data = res.data.data;
                                $scope.list = data.items;
                                _.each($scope.list, function (item) {
                                    if (+new Date(item.save_enddate) <= +new Date(SERVER_TIME.split(' ')[0])) {
                                        item._hasExpires = true
                                    }
                                });
                                $scope.total = data.total;
                            } else {
                                ui.showErrTip(res.data.errMsg);
                                return false;
                            }
                        })
                }

                //点击查询按钮
                $scope.getFilterData = function () {
                    $scope.searchStatus = '2';
                    $scope.pageIndex = 1;
                    doGetFilter();
                };

                /*分页*/
                $scope.getCustomerData = function (pageIndex) {
                    $scope.pageIndex = pageIndex;
                    switch ($scope.searchStatus) {
                        case '0':
                            return getData();
                            break;
                        case '1':
                            return searchByKeyword();
                            break;
                        case '2':
                            return doGetFilter();
                            break;
                    }
                };

                //检查是否需要另开页面下载
                $scope.beforeExportData = function(params,type){
                    var taskId = false;
                    $.ajax({
                        type: 'POST',
                        async:false,
                        data:params,
                        url: api_prefix + "check-export-customer-manage-need-task&token="+util.getToken()+'&exportType='+type,
                        success: function(re) {
                            if(re.data.needTask){
                                taskId = re.data.taskId;
                            }
                        },
                        error:function(){

                        }
                    });
                    return taskId;
                };


                //导出客户列表
                $scope.exportData = function (e) {
                    var downloadURL = '';
                    switch ($scope.searchStatus) {
                        case '0':
                            var params = {
                                projectId: $scope.projectId
                            };
                            var task = $scope.beforeExportData(params,'default');
                            downloadURL = api_prefix + "default-search-export&" + $.param(params);
                            if(!task){
                                $(e.target).attr('href', downloadURL);
                            }else{
                                window.open('/page/export_data.shtml?taskId='+task)
                            }
                            break;
                        case '1':
                            var params = {
                                projectId: $scope.projectId,
                                type: $scope.search.type,
                                placeholder: $scope.search.keyword
                            };
                            var task = $scope.beforeExportData(params,'basis');
                            downloadURL = api_prefix + "basis-search-export&" + $.param(params);
                            if(!task){
                                $(e.target).attr('href', downloadURL);
                            }else{
                                window.open('/page/export_data.shtml?taskId='+task)
                            }
                            break;
                        case '2':
                            var belongsCompany = $scope.filter.belongsCompany || [];
                            var cstStatus = $scope.filter.cstStatus || [];
                            var shenhe = $scope.filter.shenhe || [];
                            var params = {
                                projId: $scope.projectId,
                                brokerIdentity: $scope.selectedBrokerIdentity,
                                belongsCompany: belongsCompany.join(","),
                                cstStatus: cstStatus.join(","),
                                checkStatus: shenhe.join(","),
                                sTime: $scope.filter.startDate,
                                eTime: $scope.filter.endDate
                            };
                            var task = $scope.beforeExportData(params,'advanced');
                            downloadURL = api_prefix + "advanced-search-export&" + $.param(params);
                            if(!task){
                                $(e.target).attr('href', downloadURL);
                            }else{
                                window.open('/page/export_data.shtml?taskId='+task)
                            }
                            break;
                    }

                };

                /**
                 * 是否能修改状态
                 * @param {Object} item
                 * @returns {boolean}
                 */
                $scope.canChangeStatus = function (item) {
                    return util.inArray(item.cst_status + '_' + item.check_status, ['3_2', '4_6', '4_7']) && (item.can_modify == '2');
                };

                /**
                 * 获取可更改的状态
                 * @param {Object} item
                 * @returns {Array}
                 */
                var getSelectableStatus = function (item) {
                    var mapOri = [
                        {
                            status: '3_2',
                            value: '0',
                            name: '未认筹'
                        },
                        {
                            status: '4_6',
                            value: '1',
                            name: '已认筹'
                        },
                        {
                            status: '4_7',
                            value: '2',
                            name: '已认购'
                        },
                        {
                            status: '4_8',
                            value: '3',
                            name: '已签约'
                        }
                    ];

                    var status = item.cst_status + '_' + item.check_status;

                    var res = [];
                    var it;
                    for (var i = 0; it = mapOri[i]; i++) {
                        if (it.status !== status) {
                            res.push(it);
                        }
                    }

                    return res;
                };

                var getSelectAbleStatus = function (item) {
                    var mapOri = [
                        {
                            status: '3_2',
                            value: '0',
                            name: '未认筹'
                        },
                        {
                            status: '4_6',
                            value: '1',
                            name: '已认筹'
                        },
                        {
                            status: '4_7',
                            value: '2',
                            name: '已认购'
                        },
                        {
                            status: '4_8',
                            value: '3',
                            name: '已签约'
                        }
                    ];

                    var status = item.cst_status + '_' + item.check_status;

                    var res = [];
                    var it;
                    for (var i = 0; it = mapOri[i]; i++) {
                        if (it.status !== status) {
                            res.push(it);
                        }
                    }

                    return res;
                };

                $scope.showChangeStatus = function (data, dialog, dialogScope) {
                    dialogScope.selectableStatus = getSelectAbleStatus(data);
                };

                /**
                 * 修改客户状态
                 * @param data
                 * @param dialog
                 */
                $scope.changeStatus = function (data, dialog) {
                    return $http.post(api_prefix + 'chg-cst-status', {
                        'b_regbroker_cst_projId': data.b_regbroker_cst_projId,
                        'proj_id': $scope.projectId,
                        'old_cst_status': '',
                        'new_cst_status': data.new_cst_status,
                        'check_date': data.check_date
                    })
                        .success(function (res) {
                            if (res.retCode == 0) {
                                $scope.getCustomerData($scope.pageIndex).finally(function () {
                                    ui.showSucTip();
                                });
                            }
                        })
                };

                //查看详情
                $scope.showSeeDetails = function (data, dialog, $dialogScope) {
                    dialog.button([]);
                    $dialogScope.closeCustomerDetails = function () {
                        dialog.close();
                    };
                    $dialogScope.canChangeStatus = $scope.canChangeStatus;
                    $dialogScope.showChangeStatus = $scope.showChangeStatus;
                    $dialogScope.changeStatus = function () {
                        $scope.changeStatus.apply($scope, arguments)
                            .finally(function () {
                                dialog.close();
                            })
                    }
                };

                var getFromFilter = false;
                var search = $location.search();
                if (search['filterDate'] === 'cur') {
                    var today = new Date();
                    $scope.filter.startDate = util.formatDate(new Date(today - 24 * 3600 * 1000), 'yyyy-MM-dd');
                    $scope.filter.endDate = util.formatDate(today, 'yyyy-MM-dd');
                    getFromFilter = true;
                }

                if (typeof search['shenhe'] == 'string') {
                    var shenhe = search['shenhe'].split(',');

                    var shenheList = $scope.ShenheList;
                    var item;
                    for (var i = 0; item = shenheList[i]; i++) {
                        if (util.inArray(item.shenhe, shenhe)) {
                            item.selected = true;
                        }
                    }

                    $scope.filter.shenhe = shenhe;

                    getFromFilter = true;
                }

                function getData() {
                    if (getFromFilter) {
                        getFromFilter = false;
                        return doGetFilter();
                    } else {
                        var params = {
                            proId: $scope.projectId,
                            curPage: $scope.pageIndex,
                            pageSize: $scope.filter.pageSize
                        };
                        $scope.loading = true;
                        return $http
                            .get(api_prefix + "default-search", {params: params})
                            .then(function (res) {
                                $scope.loading = false;
                                var retCode = res.data.retCode;
                                if (retCode == 0) {
                                    var data = res.data.data;
                                    $scope.brokerIdentity = data.brokerIdentity;
                                    $scope.list = data.items;
                                    _.each($scope.list, function (item) {
                                        if (+new Date(item.save_enddate) <= +new Date(SERVER_TIME.split(' ')[0])) {
                                            item._hasExpires = true
                                        }
                                    });
                                    $scope.total = data.total;
                                } else {
                                    ui.showErrTip(res.data.errMsg);
                                    return false;
                                }
                            })
                            .finally(function () {
                                $scope.loading = false;
                            });
                    }
                }

                var update = function (projectId) {
                    $scope.projectId = projectId;
                    $scope.searchStatus = '0';
                    $scope.pageIndex = 1;
                    getData();
                };

                projectList.then(
                    function (res) {
                        $scope.projectList = res.data.data;
                        $scope.current = $location.path();
                    }
                );

                $scope.$watch('curProjectId', function () {
                    if ($scope.curProjectId) {
                        update($scope.curProjectId);
                    }
                });

            }]);


    angular.bootstrap(document, ['app']);
})
